<template>
  <div class="merchant-account">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.name" placeholder="请输入商家名称" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item label="账户状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
            <el-option label="待审核" value="pending" />
            <el-option label="审核拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd" v-permission="'merchant:account:add'">
        <el-icon><Plus /></el-icon>新增商家
      </el-button>
      <el-button type="success" @click="handleExport" v-permission="'merchant:account:export'">
        <el-icon><Download /></el-icon>导出数据
      </el-button>
      <el-button type="danger" :disabled="!selectedAccounts.length" @click="handleBatchDelete" v-permission="'merchant:account:delete'">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
    </div>

    <!-- 商家账户列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="accountList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="商家名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="email" label="电子邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="账户状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAccountStatusTag(row.status)">
              {{ getAccountStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" min-width="180" />
        <el-table-column prop="createTime" label="注册时间" min-width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)" v-permission="'merchant:account:edit'">
              编辑
            </el-button>
            <el-button type="primary" link @click="handlePermission(row)" v-permission="'merchant:account:permission'">
              权限
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(row)"
              v-permission="'merchant:account:status'"
            >
              {{ row.status === 'normal' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="primary" link @click="handleResetPassword(row)" v-permission="'merchant:account:password'">
              重置密码
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)" v-permission="'merchant:account:delete'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑商家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商家' : '编辑商家'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入登录密码" show-password />
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
            <el-option label="待审核" value="pending" />
            <el-option label="审核拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="500px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        label-width="100px"
      >
        <el-form-item label="角色">
          <el-select v-model="permissionForm.roles" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :props="{ label: 'name' }"
            :default-checked-keys="permissionForm.permissions"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import {
  getMerchantAccountList,
  getMerchantAccountDetail,
  createMerchantAccount,
  updateMerchantAccount,
  deleteMerchantAccount,
  batchDeleteMerchantAccounts,
  updateMerchantAccountStatus,
  resetMerchantPassword,
  getMerchantRoles,
  getMerchantPermissions,
  updateMerchantPermissions,
  exportMerchantAccounts
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  status: '',
  dateRange: []
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 商家账户列表数据
const loading = ref(false)
const accountList = ref([])
const selectedAccounts = ref([])

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  phone: '',
  email: '',
  password: '',
  status: 'normal',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择账户状态', trigger: 'change' }
  ]
}

// 权限设置对话框
const permissionDialogVisible = ref(false)
const permissionFormRef = ref(null)
const permissionTreeRef = ref(null)
const permissionForm = reactive({
  roles: [],
  permissions: []
})
const roleOptions = ref([])
const permissionTree = ref([])
const currentAccountId = ref(null)

// 获取商家账户列表
const getAccountListData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantAccountList(params)
    accountList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取商家账户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const { data } = await getMerchantRoles()
    roleOptions.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 获取权限树
const getPermissionTree = async () => {
  try {
    const { data } = await getMerchantPermissions()
    permissionTree.value = data
  } catch (error) {
    console.error('获取权限树失败:', error)
  }
}

// 获取账户状态标签
const getAccountStatusTag = (status) => {
  const statusMap = {
    normal: 'success',
    disabled: 'danger',
    pending: 'warning',
    rejected: 'info'
  }
  return statusMap[status] || ''
}

// 获取账户状态标签文本
const getAccountStatusLabel = (status) => {
  const statusMap = {
    normal: '正常',
    disabled: '禁用',
    pending: '待审核',
    rejected: '审核拒绝'
  }
  return statusMap[status] || status
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getAccountListData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedAccounts.value = selection
}

// 新增商家
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    if (key === 'status') {
      form[key] = 'normal'
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑商家
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    const { data } = await getMerchantAccountDetail(row.id)
    Object.keys(form).forEach(key => {
      if (key !== 'password') {
        form[key] = data[key]
      }
    })
    dialogVisible.value = true
  } catch (error) {
    console.error('获取商家详情失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await createMerchantAccount(form)
      ElMessage.success('新增成功')
    } else {
      await updateMerchantAccount(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getAccountListData()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 删除商家
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该商家账户吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantAccount(row.id)
    ElMessage.success('删除成功')
    getAccountListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商家账户失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedAccounts.value.length) return
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedAccounts.value.length} 个商家账户吗？`, '提示', {
      type: 'warning'
    })
    const ids = selectedAccounts.value.map(item => item.id)
    await batchDeleteMerchantAccounts(ids)
    ElMessage.success('批量删除成功')
    getAccountListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除商家账户失败:', error)
    }
  }
}

// 切换账户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 'normal' ? 'disabled' : 'normal'
  const actionText = newStatus === 'normal' ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(`确认${actionText}该商家账户吗？`, '提示', {
      type: 'warning'
    })
    await updateMerchantAccountStatus(row.id, newStatus)
    ElMessage.success(`${actionText}成功`)
    getAccountListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新商家账户状态失败:', error)
    }
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm('确认重置该商家账户的登录密码吗？', '提示', {
      type: 'warning'
    })
    await resetMerchantPassword(row.id)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
    }
  }
}

// 权限设置
const handlePermission = async (row) => {
  currentAccountId.value = row.id
  try {
    const [rolesRes, permissionsRes] = await Promise.all([
      getMerchantRoles(),
      getMerchantPermissions()
    ])
    roleOptions.value = rolesRes.data
    permissionTree.value = permissionsRes.data
    permissionForm.roles = row.roles || []
    permissionForm.permissions = row.permissions || []
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限数据失败:', error)
  }
}

// 提交权限设置
const handlePermissionSubmit = async () => {
  if (!currentAccountId.value) return
  
  try {
    const permissions = permissionTreeRef.value.getCheckedKeys()
    await updateMerchantPermissions(currentAccountId.value, {
      roles: permissionForm.roles,
      permissions
    })
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
    getAccountListData()
  } catch (error) {
    console.error('更新权限设置失败:', error)
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantAccounts(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getAccountListData()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getAccountListData()
}

onMounted(() => {
  getAccountListData()
  getRoleList()
  getPermissionTree()
})
</script>

<style lang="scss" scoped>
.merchant-account {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 